﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SharpArch.Core.PersistenceSupport;
using TrilhaImovel.Core.Entities;
using TrilhaImovel.Data;
using TrilhaImovel.UI.Controllers.Properties;
using TrilhaImovel.Core.Repositories;

namespace TrilhaImovel.UI.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        private readonly IGeocodingLogRepository geocodingLogRepository;

        public HomeController(IGeocodingLogRepository repository)
        {
            geocodingLogRepository = repository;
        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Temp()
        {
            return View();
        }

        [HttpPost]
        public void RegisterGeocodingUse()
        {
            // TODO: Tratar concorrência de acesso. Vários usuários acessando simultaneamente o trilha e geocoding. Transação é uma opção aceitável para o inicio?

            DateTime now = DateTime.Now;
            
            GeocodingLog currentLog = geocodingLogRepository.GetGeocodinglog(now.Year, now.Month, now.Day);

            if (currentLog == null)
            {
                currentLog = new GeocodingLog();
            }

            currentLog.SetNewAcess();
            geocodingLogRepository.SaveOrUpdate(currentLog);
            geocodingLogRepository.DbContext.CommitChanges();
        }

        [HttpPost]
        public JsonResult IsAllowedGeocodingUse()
        {
            bool result = true;
            DateTime now = DateTime.Now;
            
            GeocodingLog currentLog = geocodingLogRepository.GetGeocodinglog(now.Year, now.Month, now.Day);

            if (currentLog != null)
            {
                result = currentLog.IsGeocodingAcessible(Settings.Default.GoogleGeocodingLimitNumber);
            }
            
            return Json(result);
        }
    }
}
